const app = getApp();

Page({
  data: {
    // 消息列表
    messageList: [],
    // 输入框内容
    inputText: '',
    // 当前用户ID
    currentUserId: null,
    // 伴侣信息
    partnerInfo: null,
    // WebSocket连接状态
    socketConnected: false,
    // 页面滚动到底部标识
    scrollToBottom: false,
    // 消息发送状态
    sendingMessage: false,
    // 未读消息数量
    unreadCount: 0,
    // 消息类型选择
    showMessageType: false,
    messageTypes: [
      { type: 'text', name: '文字消息', icon: '💬' },
      { type: 'image', name: '图片消息', icon: '📷' },
      { type: 'audio', name: '语音消息', icon: '🎤' }
    ],
    // 录音相关
    isRecording: false,
    recordTime: 0,
    recordTimer: null
  },

  onLoad(options) {
    this.setData({
      currentUserId: wx.getStorageSync('userId')
    });
    
    this.loadPartnerInfo();
    this.loadMessageHistory();
    this.connectWebSocket();
  },

  onShow() {
    // 标记消息为已读
    this.markMessagesAsRead();
  },

  onUnload() {
    // 断开WebSocket连接
    if (this.data.socketConnected) {
      wx.closeSocket();
    }
    
    // 清除录音定时器
    if (this.data.recordTimer) {
      clearInterval(this.data.recordTimer);
    }
  },

  /**
   * 加载伴侣信息
   */
  loadPartnerInfo() {
    wx.request({
      url: `${app.globalData.baseUrl}/users/partner`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          this.setData({
            partnerInfo: res.data.data
          });
        }
      },
      fail: (err) => {
        console.error('加载伴侣信息失败:', err);
      }
    });
  },

  /**
   * 加载消息历史
   */
  loadMessageHistory() {
    if (!this.data.partnerInfo) {
      setTimeout(() => this.loadMessageHistory(), 500);
      return;
    }

    wx.request({
      url: `${app.globalData.baseUrl}/messages/chat-history`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        partnerId: this.data.partnerInfo.id,
        page: 1,
        size: 50
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            messageList: res.data.data.records || [],
            scrollToBottom: true
          });
        }
      },
      fail: (err) => {
        console.error('加载消息历史失败:', err);
      }
    });
  },

  /**
   * 连接WebSocket
   */
  connectWebSocket() {
    const token = wx.getStorageSync('token');
    
    wx.connectSocket({
      url: `${app.globalData.wsUrl}/ws?token=${token}`
    });

    wx.onSocketOpen(() => {
      console.log('WebSocket连接已打开');
      this.setData({ socketConnected: true });
      
      // 订阅消息
      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 'subscribe',
          channel: 'message'
        })
      });
    });

    wx.onSocketMessage((res) => {
      try {
        const message = JSON.parse(res.data);
        this.handleWebSocketMessage(message);
      } catch (e) {
        console.error('解析WebSocket消息失败:', e);
      }
    });

    wx.onSocketError((err) => {
      console.error('WebSocket连接错误:', err);
      this.setData({ socketConnected: false });
    });

    wx.onSocketClose(() => {
      console.log('WebSocket连接已关闭');
      this.setData({ socketConnected: false });
      
      // 尝试重连
      setTimeout(() => {
        this.connectWebSocket();
      }, 3000);
    });
  },

  /**
   * 处理WebSocket消息
   */
  handleWebSocketMessage(message) {
    switch (message.type) {
      case 'new_message':
        this.addNewMessage(message.data);
        break;
      case 'message_read':
        this.updateMessageReadStatus(message.data);
        break;
      default:
        console.log('未知消息类型:', message.type);
    }
  },

  /**
   * 添加新消息
   */
  addNewMessage(messageData) {
    const messageList = [...this.data.messageList, messageData];
    this.setData({
      messageList,
      scrollToBottom: true
    });
    
    // 如果不是当前用户发送的消息，标记为已读
    if (messageData.senderId !== this.data.currentUserId) {
      this.markMessagesAsRead();
    }
  },

  /**
   * 更新消息已读状态
   */
  updateMessageReadStatus(data) {
    const messageList = this.data.messageList.map(msg => {
      if (msg.id === data.messageId) {
        return { ...msg, isRead: true, readTime: data.readTime };
      }
      return msg;
    });
    
    this.setData({ messageList });
  },

  /**
   * 标记消息为已读
   */
  markMessagesAsRead() {
    if (!this.data.partnerInfo) return;
    
    wx.request({
      url: `${app.globalData.baseUrl}/messages/mark-read`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      data: {
        senderId: this.data.partnerInfo.id
      },
      success: (res) => {
        if (res.data.code === 200) {
          console.log('消息已标记为已读');
        }
      }
    });
  },

  /**
   * 输入框内容变化
   */
  onInputChange(e) {
    this.setData({
      inputText: e.detail.value
    });
  },

  /**
   * 发送文字消息
   */
  sendTextMessage() {
    const { inputText, partnerInfo, sendingMessage } = this.data;
    
    if (!inputText.trim()) {
      wx.showToast({ title: '请输入消息内容', icon: 'none' });
      return;
    }
    
    if (!partnerInfo) {
      wx.showToast({ title: '未找到伴侣信息', icon: 'none' });
      return;
    }
    
    if (sendingMessage) {
      return;
    }
    
    this.setData({ sendingMessage: true });
    
    wx.request({
      url: `${app.globalData.baseUrl}/messages/send-text`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      data: {
        receiverId: partnerInfo.id,
        content: inputText.trim()
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            inputText: '',
            sendingMessage: false
          });
          
          // 添加到消息列表
          this.addNewMessage(res.data.data);
        } else {
          wx.showToast({ title: res.data.message || '发送失败', icon: 'none' });
          this.setData({ sendingMessage: false });
        }
      },
      fail: (err) => {
        console.error('发送消息失败:', err);
        wx.showToast({ title: '发送失败', icon: 'none' });
        this.setData({ sendingMessage: false });
      }
    });
  },

  /**
   * 选择图片并发送
   */
  sendImageMessage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAndSendImage(tempFilePath);
      }
    });
  },

  /**
   * 上传并发送图片
   */
  uploadAndSendImage(filePath) {
    wx.showLoading({ title: '发送中...' });
    
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/upload/image`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          // 发送图片消息
          this.sendMediaMessage('image', data.data.url);
        } else {
          wx.showToast({ title: '图片上传失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('图片上传失败:', err);
        wx.showToast({ title: '图片上传失败', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * 发送媒体消息
   */
  sendMediaMessage(type, mediaUrl) {
    const { partnerInfo } = this.data;
    
    if (!partnerInfo) {
      wx.showToast({ title: '未找到伴侣信息', icon: 'none' });
      return;
    }
    
    wx.request({
      url: `${app.globalData.baseUrl}/messages/send-${type}`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      data: {
        receiverId: partnerInfo.id,
        mediaUrl: mediaUrl
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.addNewMessage(res.data.data);
        } else {
          wx.showToast({ title: res.data.message || '发送失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('发送媒体消息失败:', err);
        wx.showToast({ title: '发送失败', icon: 'none' });
      }
    });
  },

  /**
   * 开始录音
   */
  startRecording() {
    wx.authorize({
      scope: 'scope.record',
      success: () => {
        const recorderManager = wx.getRecorderManager();
        
        recorderManager.start({
          duration: 60000, // 最长60秒
          sampleRate: 16000,
          numberOfChannels: 1,
          encodeBitRate: 96000,
          format: 'mp3'
        });
        
        this.setData({
          isRecording: true,
          recordTime: 0
        });
        
        // 开始计时
        const timer = setInterval(() => {
          const recordTime = this.data.recordTime + 1;
          this.setData({ recordTime });
          
          if (recordTime >= 60) {
            this.stopRecording();
          }
        }, 1000);
        
        this.setData({ recordTimer: timer });
        
        recorderManager.onStop((res) => {
          this.handleRecordingStop(res);
        });
      },
      fail: () => {
        wx.showToast({ title: '需要录音权限', icon: 'none' });
      }
    });
  },

  /**
   * 停止录音
   */
  stopRecording() {
    const recorderManager = wx.getRecorderManager();
    recorderManager.stop();
    
    this.setData({ isRecording: false });
    
    if (this.data.recordTimer) {
      clearInterval(this.data.recordTimer);
      this.setData({ recordTimer: null });
    }
  },

  /**
   * 处理录音结束
   */
  handleRecordingStop(res) {
    if (res.duration < 1000) {
      wx.showToast({ title: '录音时间太短', icon: 'none' });
      return;
    }
    
    this.uploadAndSendAudio(res.tempFilePath, res.duration);
  },

  /**
   * 上传并发送语音
   */
  uploadAndSendAudio(filePath, duration) {
    wx.showLoading({ title: '发送中...' });
    
    wx.uploadFile({
      url: `${app.globalData.baseUrl}/upload/audio`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      formData: {
        duration: Math.floor(duration / 1000)
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          this.sendMediaMessage('audio', data.data.url);
        } else {
          wx.showToast({ title: '语音上传失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('语音上传失败:', err);
        wx.showToast({ title: '语音上传失败', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  /**
   * 播放语音消息
   */
  playAudioMessage(e) {
    const { url } = e.currentTarget.dataset;
    
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.src = url;
    innerAudioContext.play();
    
    innerAudioContext.onError((err) => {
      console.error('播放语音失败:', err);
      wx.showToast({ title: '播放失败', icon: 'none' });
    });
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const { url } = e.currentTarget.dataset;
    
    wx.previewImage({
      urls: [url],
      current: url
    });
  },

  /**
   * 显示消息类型选择
   */
  showMessageTypeSelector() {
    this.setData({ showMessageType: true });
  },

  /**
   * 隐藏消息类型选择
   */
  hideMessageTypeSelector() {
    this.setData({ showMessageType: false });
  },

  /**
   * 选择消息类型
   */
  selectMessageType(e) {
    const { type } = e.currentTarget.dataset;
    
    this.hideMessageTypeSelector();
    
    switch (type) {
      case 'image':
        this.sendImageMessage();
        break;
      case 'audio':
        this.startRecording();
        break;
      default:
        break;
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    if (diff < 60000) { // 1分钟内
      return '刚刚';
    } else if (diff < 3600000) { // 1小时内
      return `${Math.floor(diff / 60000)}分钟前`;
    } else if (diff < 86400000) { // 24小时内
      return `${Math.floor(diff / 3600000)}小时前`;
    } else {
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  },

  /**
   * 格式化语音时长
   */
  formatDuration(seconds) {
    if (seconds < 60) {
      return `${seconds}''`;
    } else {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes}'${remainingSeconds}''`;
    }
  }
});